package com.lsh.payment.core.strategy.payment;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.payment.api.model.basevo.ExceptionStatus;
import com.lsh.payment.core.constant.BusinessConstant;
import com.lsh.payment.core.exception.BusinessException;
import com.lsh.payment.core.strategy.vo.dmallpay.DMallPayResponse;
import com.lsh.payment.core.util.HttpClientUtils;
import com.lsh.payment.core.util.MD5Util;
import com.lsh.payment.core.util.pay.dmallpay.DMallSignature;
import org.slf4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 微信app支付
 * Project Name: lsh-payment
 * Created by peter on 16/10/30.
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Component
@Lazy(value = false)
public class DMallPayStrategy implements PayStrategy<DMallPayResponse>, InitializingBean {

    private static Logger logger = org.slf4j.LoggerFactory.getLogger(DMallPayStrategy.class);

    @Override
    public DMallPayResponse generatePayParams(int payType, final Map<String, String> paramMap) {
        DMallPayResponse dMallPayResponse = new DMallPayResponse();

        JSONArray wares = JSONArray.parseArray(paramMap.get("wares"));

        //组装request对象
        Map<String, Object> dMallParams = new HashMap<>();
        dMallParams.put("vendorId", Long.valueOf(paramMap.get("vendorId")));
        dMallParams.put("storeId", Long.valueOf(paramMap.get("storeId")));
        dMallParams.put("thirdOrderId", paramMap.get("thirdOrderId"));
        dMallParams.put("terminal", paramMap.get("terminal"));
        dMallParams.put("channel", paramMap.get("channel"));
        dMallParams.put("discountPrice", Long.valueOf(paramMap.get("discountPrice")));
        dMallParams.put("originPrice", Long.valueOf(paramMap.get("originPrice")));
        dMallParams.put("discountAmount", Long.valueOf(paramMap.get("discountAmount")));
        dMallParams.put("wares", wares);
        dMallParams.put("nonceStr", MD5Util.generateNonceStr());

        //生成签名
        logger.info("申请授权数据 : " + JSON.toJSONString(dMallParams));
        String sign = DMallSignature.sign(dMallParams, paramMap.get("key"));
        logger.info("签名 : " + sign);

        //组装请求多点对象
        Map<String, Object> requestParams = new TreeMap<>();
        requestParams.put("param", JSON.toJSONString(dMallParams));
        requestParams.put("sign", sign);

        //请求URL
        String url = paramMap.get("url");

        //请求Header
        Map<String, String> header = new HashMap<>(5);
        header.put("Content-Type", "application/x-www-form-urlencoded");

        //请求多点
        logger.info("请求多点下单,请求头:" + JSON.toJSONString(header) + ", 参数" + JSON.toJSONString(requestParams));
        String resultString = HttpClientUtils.doPost(url, requestParams, header);
        logger.info("请求多点下单,返回:" + resultString);

        if (StringUtils.isBlank(resultString)) {
            throw new BusinessException(ExceptionStatus.E2001005.getCode(), ExceptionStatus.E2001005.getMessage());
        }
        JSONObject resultObject = JSONObject.parseObject(resultString);
        dMallPayResponse.setCode(resultObject.getString("code"));
        dMallPayResponse.setMsg(resultObject.getString("sourceMsg"));
        dMallPayResponse.setResult(resultObject.getString("result"));
        dMallPayResponse.setSuccess(resultObject.getBoolean("success"));
        if (dMallPayResponse.getCode().equals(BusinessConstant.DMALL_REQUEST_SUCCESS)
                && Boolean.TRUE.equals(dMallPayResponse.getSuccess())) {
            DMallPayResponse.Data data = dMallPayResponse.new Data();
            JSONObject dataObject = resultObject.getJSONObject("data");

            data.setCartId(dataObject.getString("cartId"));
            data.setSum(dataObject.getInteger("sum"));
            data.setCount(dataObject.getInteger("count"));
            data.setQrstr(dataObject.getString("qrstr"));
            data.setDiscountPrice(dataObject.getLong("discountPrice"));
            data.setOriginPrice(dataObject.getLong("originPrice"));
            data.setDiscountAmount(dataObject.getLong("discountAmount"));
            data.setStoreId(dataObject.getLong("storeId"));

            dMallPayResponse.setData(data);
        }

        return dMallPayResponse;
    }

    @Override
    public void afterPropertiesSet() throws BusinessException {
        PayStrategyFactory.register(BusinessConstant.DMALLPAY, this);
    }
}
